package demo6;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
public class DBQueryTest {
    // MySQL配置（匹配你的环境）
    private static final String URL = "jdbc:mysql://localhost:3306/test_db?useSSL=false&characterEncoding=utf8";
    private static final String USER = "root";
    private static final String PASSWORD = "122605";
    public static void main(String[] args) {
        Connection conn = null;
        QueryRunner queryRunner = new QueryRunner(); // DBUtils的核心类
        try {
            // 1. 获取连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
            System.out.println("✅ MySQL + DBUtils 连接成功！");
            // 2. 插入数据（DBUtils的update方法）
            String insertSql = "INSERT INTO user(username, password) VALUES (?, ?)";
            int affectedRows = queryRunner.update(conn, insertSql, "zhangshun", "567890");
            System.out.println("插入成功，影响行数：" + affectedRows);
            // 3. 查询数据（DBUtils的query方法 + BeanListHandler）
            String selectSql = "SELECT id, username, password FROM user";
            List<User> userList = queryRunner.query(conn, selectSql, new BeanListHandler<>(User.class));
            System.out.println("\n📋 当前user表数据：");
            for (User user : userList) {
                System.out.println(user);
            }
        } catch (Exception e) {
            System.out.println("❌ 操作失败：" + e.getMessage());
        } finally {
            // 4. 关闭连接（DBUtils的工具方法）
            try {
                DbUtils.close(conn);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
